#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose: Export system
# Created: 02/24/2009
# $Id $
# Copyright (c) 2008,2009 by University College London
# Authors:
# Didrik Pinte --<dpinte@dipole-consulting.com>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.

import inspect

import xlwt

from hydroplatform.model import network as nt

class ExportError(Exception):
    pass

class Exporter(object):
    '''
    This is a default class for export. Exporters should implement the methods
    from this class 
    '''
    _name = "Exporter"
    _description = "Basic text exporter to file"
    
    def __init__(self):
        object.__init__(self)
    
    def getName(self):
        return self._name
    
    def getDescription(self):
        return self._description
    
    def export(self, network, filename, session=None):
        '''
        Export an hydroplatform.model.network.Network to the given filename
        
        FIXME : filename could be a file like object
        '''
        stream = open(filename, 'w', 1)
        assert isinstance(network, nt.Network)
        for node in network.nodes:
            stream.write(node.getName())
            stream.write('\n')
        for link in network.links:
            stream.write(link.getName())
            stream.write('\n')
        stream.close()
            

class ExporterRegistry(object):
    '''
    This is a Borg class allowing to acces the exporters throughout the application
    '''
    _state = {}
    
    def __new__(cls, *p, **k):
        self = object.__new__(cls, *p, **k)
        self.__dict__ = cls._state
        return self
    
    def __init__(self):
        if not hasattr(self, 'exporters'):
            self.exporters = set()
  
    def register(self, exporter):
        if inspect.isclass(exporter):
            instance = exporter()        
            self.exporters.add(instance) 
        else: 
            self.exporters.add(exporter)
        
    def available_exporters(self):
        '''
        Return the list of available exporters
        '''
        return list(self.exporters)
    
    def getExporterByName(self, name):
        for exporter in self.exporters:
            if exporter.getName() == name:
                return exporter
    
    def export_network(self, exporter, network, filename, session=None):
        try:
            exporter.export(network, filename, session)
        except ExportError, e:
            raise e 
